package com.hd.sup.modules.vehicle.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.common.constant.BizConstant;
import com.hd.common.utils.GenUtil;
import com.hd.common.utils.StrUtils;
import com.hd.sup.config.redis.prefix.CacheKey;
import com.hd.sup.config.redis.utils.JedisUtil;
import com.hd.sup.core.rest.dto.TData;
import com.hd.sup.modules.vehicle.mapper.VehicleMapper;
import com.hd.sup.modules.vehicle.model.Vehicle;
import com.hd.sup.modules.vehicle.service.IVehicleEndPosService;
import com.hd.sup.modules.vehicle.service.IVehicleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 车辆信息表 服务实现类
 * </p>
 *
 * @author chentl123
 * @since 2020-12-28
 */
@Slf4j
@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements IVehicleService {


    @Resource
    private JedisUtil jedisUtil;

    @Resource
    private IVehicleEndPosService vehicleEndPosService;

    @Override
    public List<Map<String, Object>> pageList(Page page, Vehicle vehicle) {
        return this.baseMapper.pageList(page, vehicle);
    }

    @Override
    public List<Map<String, Object>> getAllVehicleMap(String regionCode, Integer lengthL, Integer lengthR) {
        return this.baseMapper.getAllVehicleMap(regionCode, lengthL, lengthR);
    }

    @Override
    public Integer countVehicleNum(String regionCode, String transType, List<String> deptIds) {
        return this.baseMapper.countVehicleNum(regionCode, transType, deptIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateVehicle(List<TData> data, String enterpriseNo, String enterpriseName) {
        if (CollectionUtils.isNotEmpty(data)) {
            //TIP data.size() 逻辑上只有1条。 此处兼容 多颜色车牌 的情况出现
            data.forEach(one -> {
                String platNo = one.getVehicleid();
                String platNoColor = one.getVclidcolor();
                int v_db = this.baseMapper.selectCount(new LambdaQueryWrapper<Vehicle>().eq(Vehicle::getPlatNo, platNo).eq(Vehicle::getPlatNoColor, platNoColor));
                if (v_db == 0) {
                    //入库车辆
                    Vehicle vc = new Vehicle(platNo, enterpriseNo, one.getDeptId(), enterpriseName, one.getVcltype(), BizConstant.VehicleTransType.getTransTypeKeyByRule(one.getMgrarea()).key(), platNoColor, one.getMgrarea(), StrUtils.cutSuffixZero(one.getOrigziparea()), enterpriseNo, one.getCorporation(), one.getMobile(), one.getMgrarea());
                    vc.insert();
                    log.info("[schedule] 车辆静态信息已入库,车牌号:{} 车牌颜色:{}", platNo, platNoColor);

                    //缓存车辆静态信息
                    jedisUtil.hset(CacheKey.STATIC_DATA_VEHICLE, GenUtil.cacheKey(platNo, BizConstant.Common.UNDERLINE.key(), platNoColor), JSON.toJSONString(vc));
                    log.info("[schedule] 车辆静态信息缓存已刷新,车牌号:{} 车牌颜色:{}", platNo, platNoColor);


                    //更新end_pos表 static_data_status 为 1
                    vehicleEndPosService.updateStatus(platNo, platNoColor, BizConstant.StaticDataStatus.SYNC_COMPLETED.key(), BizConstant.Common.BLACK.key());
                } else {
                    //更新end_pos表 static_data_status 为 2
                    log.warn("[supervise] 车辆已存在，不再同步静态信息");
                    vehicleEndPosService.updateStatus(platNo, platNoColor, BizConstant.StaticDataStatus.SYNC_FAILED.key(), "车辆已存在，不再同步静态信息");
                }
            });

        }
    }

    @Override
    public void deleteByIds(List<String> ids) {
        removeByIds(ids);

        //清理缓存
        List<Vehicle> enterprises = listByIds(ids);
        String[] vs = enterprises.stream().map(one -> GenUtil.cacheKey(one.getPlatNo(), BizConstant.Common.UNDERLINE.key(), one.getPlatNoColor())).toArray(String[]::new);

        jedisUtil.hdel(CacheKey.STATIC_DATA_VEHICLE, vs);
        log.info("[redis] 车辆缓存已对应删除");

    }

    @Override
    public List<Map<String, Object>> selectAllMaps() {
        return this.baseMapper.selectAllMaps();
    }
}
